<template>
  <div class="p-2">
    <!-- 顶部 Tab 切换 -->
    <el-tabs v-model="activeTab" class="accident-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="汽油爆炸" name="gasoline"></el-tab-pane>
      <el-tab-pane label="柴油爆炸" name="diesel"></el-tab-pane>
      <el-tab-pane label="液氨泄漏" name="ammonia"></el-tab-pane>
    </el-tabs>

    <!-- 添加三个容器，根据 activeTab 显示/隐藏 -->
    <div v-show="activeTab === 'gasoline'" class="tab-container">
      <el-row :gutter="40">
        <!-- 左侧输入参数部分 -->
        <el-col :span="8">
          <el-form :model="gasolineForm" label-width="200px">
            <el-form-item label="A：蒸汽云的TNT当量系数">
              <div class="param-container">
                <div class="input-with-unit">
                  <el-input-number
                    v-model="gasolineForm.A"
                    :min="0.02"
                    :max="14.9"
                    :precision="2"
                    :step="0.01"
                    :controls="false"
                    class="percent-input custom-input-number"
                  />
                </div>
                <div class="input-tip">取值范围为0.02%-14.9%</div>
              </div>
            </el-form-item>

            <el-form-item label="Qf：柴油的燃烧热kJ/kg">
              <div class="param-container">
                <el-input-number v-model="gasolineForm.Qf" :precision="0" :step="1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="Qtnt：TNT爆炸热MJ/kg">
              <div class="param-container">
                <el-input-number
                  v-model="gasolineForm.Qtnt"
                  :min="4.12"
                  :max="4.69"
                  :precision="2"
                  :step="0.01"
                  :controls="false"
                  class="custom-input-number"
                />
                <div class="input-tip">取值范围为4.12-4.69</div>
              </div>
            </el-form-item>

            <el-form-item label="Wtnt：蒸汽云的TNT当量kg">
              <div class="param-container">
                <el-input-number v-model="gasolineForm.Wtnt" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">M为柴油质量，单位吨 (A* (M*1000) *Qf) / (Qtnt*1000)</div>
              </div>
            </el-form-item>

            <el-form-item label="R：爆心距研究点的距离m">
              <div class="param-container">
                <el-input-number v-model="gasolineForm.R" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">P结果参考附列表三次根号(8*Wtnt / 10*P)</div>
              </div>
            </el-form-item>
          </el-form>

          <!-- 按钮组移到左侧面板底部 -->
          <div class="button-group">
            <el-button type="primary" @click="handleSaveGasoline">保存</el-button>
          </div>
        </el-col>

        <!-- 右侧表格部分 -->
        <el-col :span="16">
          <!-- 第一个表格 -->
          <div class="table-container">
            <div class="table-header">
              <div class="table-title">P：爆炸冲击波超压（Mpa）对人体伤害指标表</div>
              <div class="table-actions">
                <el-button type="primary" size="small" @click="handleAddRow(1)">添加行</el-button>
              </div>
            </div>
            <el-table :data="tableData1" border height="300" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="lowerLimit" label="下限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.lowerLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="upperLimit" label="上限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.upperLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="effect" label="破坏、伤害情况" min-width="200">
                <template #default="{ row }">
                  <el-input v-model="row.effect" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="deleteRow(1, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 第二个表格 -->
          <div class="table-container">
            <div class="table-header">
              <div class="table-title">P：爆炸冲击波超压（Mpa）对建筑物伤害分布表</div>
              <div class="table-actions">
                <el-button type="primary" size="small" @click="handleAddRow(2)">添加行</el-button>
              </div>
            </div>
            <el-table :data="tableData2" border height="300" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="lowerLimit" label="下限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.lowerLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="upperLimit" label="上限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.upperLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="effect" label="破坏、伤害情况" min-width="200">
                <template #default="{ row }">
                  <el-input v-model="row.effect" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="deleteRow(2, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <div v-show="activeTab === 'diesel'" class="tab-container">
      <el-row :gutter="40">
        <!-- 柴油爆炸的表单和表格 -->
        <!-- 左侧输入参数部分 -->
        <el-col :span="8">
          <el-form :model="dieselForm" label-width="200px">
            <el-form-item label="A：蒸汽云的TNT当量系数">
              <div class="param-container">
                <div class="input-with-unit">
                  <el-input-number
                    v-model="dieselForm.A"
                    :min="0.02"
                    :max="14.9"
                    :precision="2"
                    :step="0.01"
                    :controls="false"
                    class="percent-input custom-input-number"
                  />
                </div>
                <div class="input-tip">取值范围为0.02%-14.9%</div>
              </div>
            </el-form-item>

            <el-form-item label="Qf：汽油的燃烧热kJ/kg">
              <div class="param-container">
                <el-input-number v-model="dieselForm.Qf" :precision="0" :step="1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="Qtnt：TNT爆炸热MJ/kg">
              <div class="param-container">
                <el-input-number
                  v-model="dieselForm.Qtnt"
                  :min="4.12"
                  :max="4.69"
                  :precision="2"
                  :step="0.01"
                  :controls="false"
                  class="custom-input-number"
                />
                <div class="input-tip">取值范围为4.12-4.69</div>
              </div>
            </el-form-item>

            <el-form-item label="Wtnt：蒸汽云的TNT当量kg">
              <div class="param-container">
                <el-input-number v-model="dieselForm.Wtnt" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">M为汽油质量，单位吨 (A* (M*1000) *Qf) / (Qtnt*1000)</div>
              </div>
            </el-form-item>

            <el-form-item label="R：爆心距研究点的距离m">
              <div class="param-container">
                <el-input-number v-model="dieselForm.R" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">P结果参考附列表三次根号(8*Wtnt / 10*P)</div>
              </div>
            </el-form-item>
          </el-form>

          <!-- 按钮组移到左侧面板底部 -->
          <div class="button-group">
            <el-button type="primary" @click="handleSaveDiesel">保存</el-button>
          </div>
        </el-col>

        <!-- 右侧表格部分 -->
        <el-col :span="16">
          <!-- 第一个表格 -->
          <div class="table-container">
            <div class="table-header">
              <div class="table-title">P：爆炸冲击波超压（Mpa）对人体伤害指标表</div>
              <div class="table-actions">
                <el-button type="primary" size="small" @click="handleAddRow(1)">添加行</el-button>
              </div>
            </div>
            <el-table :data="tableData3" border height="300" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="lowerLimit" label="下限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.lowerLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="upperLimit" label="上限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.upperLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="effect" label="破坏、伤害情况" min-width="200">
                <template #default="{ row }">
                  <el-input v-model="row.effect" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="deleteRow(3, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 第二个表格 -->
          <div class="table-container">
            <div class="table-header">
              <div class="table-title">P：爆炸冲击波超压（Mpa）对建筑物伤害分布表</div>
              <div class="table-actions">
                <el-button type="primary" size="small" @click="handleAddRow(2)">添加行</el-button>
              </div>
            </div>
            <el-table :data="tableData4" border height="300" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="lowerLimit" label="下限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.lowerLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="upperLimit" label="上限值 (Mpa)" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.upperLimit" />
                </template>
              </el-table-column>
              <el-table-column prop="effect" label="破坏、伤害情况" min-width="200">
                <template #default="{ row }">
                  <el-input v-model="row.effect" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="deleteRow(4, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <div v-show="activeTab === 'ammonia'" class="tab-container">
      <el-row :gutter="40">
        <!-- 左侧输入参数部分 -->
        <el-col :span="8">
          <el-form :model="ammoniaForm" label-width="200px">
            <el-form-item label="C：液氨比热kJ/kg℃">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.C" :precision="1" :step="0.1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="t0：标准温度℃">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.t0" :precision="1" :step="0.1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="q：液氨汽化热kJ/kg">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.q" :precision="0" :step="1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="A：液氨分子量">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.A" :precision="0" :step="1" :controls="false" class="custom-input-number" />
              </div>
            </el-form-item>

            <el-form-item label="k：死亡浓度">
              <div class="param-container">
                <div class="input-with-unit">
                  <el-input-number v-model="ammoniaForm.k" :precision="1" :step="0.1" :controls="false" class="percent-input custom-input-number" />
                </div>
                <div class="input-tip">液氨在空气中的浓度达到0.5%时，人体吸入15-10分钟即致死</div>
              </div>
            </el-form-item>

            <el-form-item label="W：液氨蒸发量kg">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.W" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">(M*C*(t-t0))/q M为液氨质量，为界面取值，单位千克；t为容器破裂前器内介质温度，为界面取值，单位摄氏度</div>
              </div>
            </el-form-item>

            <el-form-item label="Vg：液氨蒸发气体积m3">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.Vg" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">(22.4*W/A)*(273+t0)/273</div>
              </div>
            </el-form-item>

            <el-form-item label="R：爆心距研究点的距离m">
              <div class="param-container">
                <el-input-number v-model="ammoniaForm.R" :precision="2" :step="0.1" :controls="false" class="custom-input-number" />
                <div class="input-tip">三次根号((Vg/k)/((2/3)*π))</div>
              </div>
            </el-form-item>
          </el-form>

          <!-- 按钮组 -->
          <div class="button-group">
            <el-button type="primary" @click="handleSaveAmmonia">保存</el-button>
          </div>
        </el-col>

        <!-- 右侧表格部分 -->
        <el-col :span="16">
          <!-- 表格内容与其他标签页相同，可以复用 -->
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { deepClone } from '@/utils';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 添加 tab 激活状态
const activeTab = ref('gasoline');

const gasolineForm = ref({
  'A': null,
  'Qf': null,
  'Qtnt': null,
  'P_Person': [],
  'P_Building': [],
  'Wtnt': 0,
  'R': 0
});

const dieselForm = ref({
  'A': null,
  'Qf': null,
  'Qtnt': null,
  'P_Person': [],
  'P_Building': [],
  'Wtnt': 0,
  'R': 0
});

const ammoniaForm = ref({
  'C': null,
  't0': null,
  'q': null,
  'A': null,
  'k': null,
  'W': 0,
  'Vg': 0,
  'R': 0
});

interface TableRow {
  lowerLimit: string;
  upperLimit: string;
  effect: string;
  selected?: boolean;
}

const tableData1 = ref<TableRow[]>([]);

const tableData2 = ref<TableRow[]>([]);

const tableData3 = ref<TableRow[]>([]);

const tableData4 = ref<TableRow[]>([]);

const handleAddRow = (tableIndex: number) => {
  const newRow = { lowerLimit: '', upperLimit: '', effect: '' };
  switch (tableIndex) {
    case 1:
      tableData1.value.push(newRow);
      break;
    case 2:
      tableData2.value.push(newRow);
      break;
    case 3:
      tableData3.value.push(newRow);
      break;
    case 4:
      tableData4.value.push(newRow);
      break;
  }
};

// 删除一行
const deleteRow = (tableIndex: number, index) => {
  switch (tableIndex) {
    case 1:
      tableData1.value.splice(index, 1); // 删除指定行
      break;
    case 2:
      tableData2.value.splice(index, 1); // 删除指定行
      break;
    case 3:
      tableData3.value.splice(index, 1); // 删除指定行
      break;
    case 4:
      tableData4.value.splice(index, 1); // 删除指定行
      break;
  }
};

const handleSaveGasoline = () => {
  // 保存逻辑
  const data = deepClone(gasolineForm.value);
  data.A = data.A / 100.0;
  data.P_Person = tableData1.value;
  data.P_Building = tableData2.value;
  proxy?.updateConfigByKey('acdtSim.gasolineExplosion', JSON.stringify(data));
};

const handleSaveDiesel = () => {
  // 保存逻辑
  const data = deepClone(dieselForm.value);
  data.A = data.A / 100.0;
  data.P_Person = tableData3.value;
  data.P_Building = tableData4.value;
  proxy?.updateConfigByKey('acdtSim.dieselExplosion', JSON.stringify(data));
};

const handleSaveAmmonia = () => {
  // 保存逻辑
  const data = deepClone(ammoniaForm.value);
  data.k = data.A / 100.0;
  proxy?.updateConfigByKey('acdtSim.ammoniaLeakage', JSON.stringify(data));
};

// 加载数据的方法
const loadTabData = async (tabName: string) => {
  try {
    switch (tabName) {
      case 'gasoline':
        proxy?.getConfigKey('acdtSim.gasolineExplosion').then((res) => {
          // 更新汽油爆炸相关数据
          const gasolineData = JSON.parse(res.data);
          gasolineForm.value.A = gasolineData.A * 100;
          gasolineForm.value.Qf = gasolineData.Qf;
          gasolineForm.value.Qtnt = gasolineData.Qtnt;
          gasolineForm.value.P_Person = gasolineData.P_Person;
          gasolineForm.value.P_Building = gasolineData.P_Building;
          tableData1.value = gasolineData.P_Person;
          tableData2.value = gasolineData.P_Building;
        });
        break;
      case 'diesel':
        proxy?.getConfigKey('acdtSim.dieselExplosion').then((res) => {
          const dieselData = JSON.parse(res.data);
          // 更新柴油爆炸相关数据
          dieselForm.value.A = dieselData.A * 100;
          dieselForm.value.Qf = dieselData.Qf;
          dieselForm.value.Qtnt = dieselData.Qtnt;
          tableData3.value = dieselData.P_Person;
          tableData4.value = dieselData.P_Building;
        });
        break;
      case 'ammonia':
        proxy?.getConfigKey('acdtSim.ammoniaLeakage').then((res) => {
          const ammoniaData = JSON.parse(res.data);
          // 更新液氨泄漏相关数据
          ammoniaForm.value.C = ammoniaData.C;
          ammoniaForm.value.t0 = ammoniaData.t0;
          ammoniaForm.value.q = ammoniaData.q;
          ammoniaForm.value.A = ammoniaData.A;
          ammoniaForm.value.k = ammoniaData.k * 100;
        });
        break;
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败');
  }
};

// Tab 切换事件处理
const handleTabClick = (tab: any) => {
  loadTabData(tab.props.name);
};

// 组件挂载时加载默认 tab 的数据
onMounted(() => {
  loadTabData('gasoline');
});
</script>

<style lang="scss" scoped>
.accident-tabs {
  margin-bottom: 20px;
}

.content-container {
  display: flex;
  gap: 40px;
  min-height: calc(100vh - 200px);
}

.left-panel {
  flex: 0 0 500px;
  display: flex;
  flex-direction: column;
}

.right-panel {
  flex: 1;
}

.input-tip {
  font-size: 12px;
  color: #999090;
  margin-top: 4px;
  line-height: 1.2;
}

:deep(.el-input-group__append) {
  display: none;
}

.table-container {
  margin-bottom: 20px;

  :deep(.el-table) {
    // 设置表格内容的背景色
    --el-table-tr-bg-color: #ffffff;

    // 设置滚动条样式
    .el-scrollbar__wrap {
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background: #dcdfe6;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-track {
        background: #f5f7fa;
      }
    }
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 10px;
}

.param-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.custom-input-number {
  width: 300px !important;
}

.percent-input {
  :deep(.el-input__wrapper) {
    &::after {
      content: '%';
      position: absolute;
      right: 8px;
      color: #606266;
    }
  }
}

// 添加新的样式
.el-row {
  min-height: calc(100vh - 200px);
}

.tab-container {
  margin-top: 20px;
}
</style>
